<?php
namespace app\api\controller\v1;
use app\admin\controller\Reason;
use app\admin\logic\welcome\WelcomeLogic;
use app\api\logic\GetAddressLogic;
use app\api\logic\QuanLogic;
use app\api\logic\SendMuLogic;
use app\common\logic\TechnLevelLogic;
use app\service\GaodeService;
use app\service\MoneyLogService;
use app\service\OrderService;
use GuzzleHttp\Promise\Each;
use think\Db;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
use app\service\PosterService;
use app\service\TechnService;
use app\admin\logic\ZzLogic;
use app\service\PaymentService;
use think\Log;
use think\Request;


class Lkceshi extends Base
{
	public function _initialize()
	{
		parent::_initialize();
	}


    public function refund_fa(){
        $openid = 'opx6C6vD4elzA71_uMmlvAxovti8';
        $order_info = Db::name('order')->where('id',23087)->find();
        $order_detail_title = Db::name('order_detail')->where('order_id',23087)->find();
        $proxy = Db::name('proxy')->where('proxy_id',5)->find();
        SendMuLogic::send_mu_refund($openid,$order_info,$order_detail_title,$proxy);

    }
    public function jiapingjia(){
//        $techn_id = 929;
        $insert = [];
        for ($i = 0;$i < 18; $i++){
            $insert[] = [
                'techn_id'=>$techn_id,
                'service_level'=>5,
                'title_ids'=>'[1,2,3,4,5]',
                'add_time'=>time(),
            ];
        }
        Db::name('talk')->insertAll($insert);
        echo 'id为'.$techn_id;
    }

    public function lijingjing(){
        $techn_id = 363;
        $list = Db::name('money_log')->where('identity_id',$techn_id)->select();
        echo "<table><tr><td>日期</td><td>订单号</td><td>说明</td><td>金额</td></tr>";

        foreach ($list as $value){
            if ($value['from_order_id'] > 0){
                $order = Db::name('order')->where('id',$value['from_order_id'])->find();
                echo "<tr><td>".date('Y-m-d H:i',$value['add_time'])."</td><td>'".$order['order_no']."</td><td>".$value['msg'].$value['operation_money'].'."</td><td>更改后余额'.$value['latest_money']."</td></tr>";
            }else{
                echo "<tr><td>".date('Y-m-d H:i',$value['add_time']).'</td><td></td><td>'.$value['msg'].$value['operation_money']."</td><td>更改后余额".$value['latest_money']."</td></tr>";

            }

        }
        echo "</table>";

    }
    public function changzhiqiyue(){
        $list = Db::name('order')
            ->where('add_time','between','1688140800,1690819200')
            ->where('shi',140400)
            ->select();

        $num = Db::name('order')
            ->where('add_time','between','1688140800,1690819200')
            ->where('shi',140400)
            ->count('id');
        dump($num);
        $i = 1;
        foreach ($list as $key => $value){
            $info = Db::name('techn')->where('id',$value['techn_id'])->find();
            if (empty($info)){
                echo ($i.'-'.$value['id']."<br>");
            }
            $i++;
        }
    }
    public function boer(){
        $rechn_id = 487;
        $min = strtotime('2023-08-16');
        $max = strtotime('2023-09-01');
        $jzl = TechnLevelLogic::jz_b($rechn_id,$min,$max);
        dump($jzl);
    }

    public function yang(){
        $value['id'] = 246;
        $min = strtotime('2023-08-01');
        $max = strtotime('2023-09-16');
        $jwhere['j.pay_time'] = ['between',$min.','.$max];
        $where['add_time'] = ['between',$min.','.$max];

        $price[$value['id']]['all_money'] = Db::name('order')
            ->where('techn_id',$value['id'])
            ->where($where)
            ->where('status',6)
            ->sum('price');

        $ids = Db::name('order')
            ->where('techn_id',$value['id'])
            ->where($where)
            ->column('id');
        $jz_money = Db::name('order_jz')->where('order_id','in',$ids)->sum('price');

        $list_s = Db::name('order_jz')->where('order_id','in',$ids)->select();
        $price[$value['id']]['price'] = $jz_money;


        $price[$value['id']]['order_num'] = Db::name('order_jz')
            ->alias('j')
            ->join('order_jzdetail d','j.id = d.jz_id')
            ->where('j.techn_id',$value['id'])
            ->where($jwhere)
            ->sum('d.buy_number');

        $price[$value['id']]['order_num'] += Db::name('order_upgrade')
            ->where('techn_id',$value['id'])
            ->where($where)
            ->count('id');

        $jzl = TechnLevelLogic::jz_v($value['id'],$min,$max);

        $price[$value['id']]['jzl'] = $jzl;


        $price[$value['id']]['online'] = (float)(Db::name('techn_last')->where('techn_id',$value['id'])->value('total_duration'));
        $price[$value['id']]['jifen'] = Db::name('techn_last')->where('techn_id',$value['id'])->value('total_integral');


        dump($price);
    }

    public function yinsi_f(){
        $yinsi_phone = cache('yinsi_phone_15035514195');
        dump($yinsi_phone);die;

    }

    public function tuisong(){
        $result = TechnLevelLogic::jz_b(405,1690819200,1692028800);
        dump($result);
    }



    public function zhoutian(){
        $order_list = Db::name('order')->where('add_time','between','1691251200,1691337600')->column('id');
        dump($order_list);
        $now = [];
        foreach ($order_list as $value){
            $lenth = Db::name('money_log')->where('from_order_id',$value)->count('id');
            if ($lenth > 4){
                $now[] = $value;
            }
        }
        dump($now);
    }


    public function xiaomi(){
        $lv = TechnLevelLogic::techn_add_level_jzl(1,405);
        dump($lv);
    }


    public function gia(){
    $ids = Db::name('order')->where('pay_status','<>',0)->where('status','<>',6)->select();
    foreach ($ids as $v){
        $info = Db::name('refund_log')->where('order_id',$v['id'])->value('refund_price');
        if (!empty($info)){
            Db::name('order')->where('id',$v['id'])->update(['refund_price'=>$info]);
        }
    }
    }
    public function decme(){
        $min_time = 1690819200;
        $max_time = 1690905600;
        $proxy_id = 2;
        if (!empty($min_time)){
            $owhere['o.add_time'] = ['>=',$min_time];
        }
        if (!empty($max_time)){
            $owhere['o.add_time'] = ['<',$max_time];
        }
        if (!empty($max_time) && !empty($min_time)){
            $owhere['o.add_time'] = ['between', $min_time.','.$max_time];
        }
        if (!empty($proxy_id)){
            $in = Db::name('proxy')->where('proxy_id',$proxy_id)->find();
            if ($in['is_xian'] == 1){
                $owhere['o.qu'] = $in['qu'];
            }else{
                $not = Db::name('proxy')->where('shi',$in['shi'])->where('proxy_id','<>',$in['proxy_id'])->where('is_xian',1)->column('qu');
                $owhere['o.shi'] = $in['shi'];
                if (!empty($not)){
                    $owhere['o.qu'] = ['not in',$not];
                }
            }
        }
        $owhere['o.id'] = ['>',-1];

        $data['order_money'] = Db::name('order')
            ->alias('o')
            ->where($owhere)
            ->where('o.status','<>',15)
            ->where('o.status','<>',7)
            ->where('o.status','<>',0)
            ->where('user_id','<>',299)
//            ->field('o.id,o.pay_price,o.refund_price')
            ->sum('o.pay_price+o.preferential_price');


        $data['refund'] = Db::name('order')
            ->alias('o')
            ->where('o.status','<>',0)
            ->where('o.status','<>',1)
            ->where($owhere)
            ->where('user_id','<>',299)
            ->sum('o.refund_price');


        $data['coupon'] = Db::name('order')
            ->alias('o')
            ->where('o.status','<>',15)
            ->where('o.status','<>',7)
            ->where('o.status','<>',0)
            ->where('user_id','<>',299)
            ->where($owhere)
            ->where('user_id','<>',299)
            ->sum('o.preferential_price');
        $data['have_money'] = $data['order_money'] - $data['refund'] - $data['coupon'];


        $order_ids = Db::name('order')
            ->alias('o')
            ->join('pay_log p','p.order_id = o.id')
            ->where($owhere)
            ->column('o.id');


        $data['techn_money'] = Db::name('balance')
//            ->where('identity_id','in',$techn_ids)
            ->where('order_id','in',$order_ids)
            ->where('status',1)
            ->where('balance_type',1)
            ->where('identity_type','techn')
            ->sum('yes_money');

        $data['money_car'] = Db::name('balance')
//            ->where('identity_id','in',$techn_ids)
            ->where('order_id','in',$order_ids)
            ->where('status',1)
            ->where('balance_type',2)
            ->where('identity_type','techn')
            ->sum('yes_money');


        $data['money_user'] = Db::name('balance')
            ->where('order_id','in',$order_ids)
            ->where('status',1)
            ->where('balance_type','in','3,4')
//            ->where('identity_type','techn')
            ->sum('yes_money');


        $data['order_num'] = Db::name('order')
            ->alias('o')
            ->join('pay_log p','o.id = p.order_id')
            ->where($owhere)
            ->where('o.techn_id','<>',299)
            ->count('o.id');

        $data['order_finish'] = Db::name('order')
            ->alias('o')
            ->join('pay_log p','o.id = p.order_id')
            ->where($owhere)
            ->where('o.status',6)
            ->where('o.techn_id','<>',299)
            ->count('o.id');


        $data['chouyong'] = 0;
        if ($proxy_id != null){
            $proxy_bl = Db::name('proxy')->where('proxy_id',$proxy_id)->value('commission');
            if ($proxy_bl > 0){
                $data['chouyong'] = round((Db::name('balance')
                        ->where('order_id','in',$order_ids)
                        ->where('status',1)
                        ->where('balance_type',1)
                        ->where('identity_type','proxy')
                        ->sum('price'))*$proxy_bl/100,2);

            }
        }
        $data['cleat_money'] = round($data['order_money'] - $data['techn_money'] - $data['money_car'] - $data['chouyong'] - $data['money_user'] - $data['coupon']  - $data['refund'],2);


        foreach ($data as $key=>$value){
            $data[$key]  = round($value,2);
        }
        dump($data);
    }
    public function welcome_logic(){
        $info = WelcomeLogic::get_proxy_money_data(null,null,9);
        dump($info);
    }
    public function hefei_ss()
    {
        $list = Db::name('order')
            ->alias('o')
            ->join('pay_log p', 'o.id = p.order_id')
            ->where('p.add_time', 'between', '1690560000,1690646400')
            ->where('o.shi', 340100)
            ->sum('o.pay_price');
        dump($list);
    }
    public function techn_online(){
        $list = Db::name('techn_last')->where('star_time','>',0)->select();
        foreach ($list as $value){
            $hours = (int)((time()-$value['star_time'])/3600);
            if ($hours > 0){
                Db::name('techn_last')->where('id',$value['id'])->update(['star_time'=>time(),'total_duration'=>$value['total_duration']+$hours]);
            }
        }
    }


    public function get_ey_data(){
        $min = 1689868800;
        $max = 1689955200;
        $pay = Db::name('pay_log')->where('add_time','between',$min.','.$max)->column('order_id');
        $pay_n = Db::name('pay_log')->where('add_time','between',$min.','.$max)->sum('pay_price');
        $refound = Db::name('refund_log')->where('add_time','between',$min.','.$max)->column('order_id');
        $re_n = Db::name('refund_log')->where('add_time','between',$min.','.$max)->sum('refund_price');

        foreach ($pay as $value){
            if (!in_array($value,$refound)){
//                echo $value.'/';
            }
        }
        dump($pay_n);
        dump($re_n);
        die;

        $order_list = Db::name('pay_log')
            ->alias('p')
            ->join('order o','o.id = p.order_id')
            ->where('p.add_time','between',$min.','.$max)
            ->where('o.status',6)
            ->join('user u','u.id = o.user_id')
            ->field('o.id,o.user_id,u.nickname,o.pay_price')
            ->order('p.add_time desc')
            ->select();

        $num = Db::name('pay_log')
            ->alias('p')
            ->join('order o','o.id = p.order_id')
            ->where('p.add_time','between',$min.','.$max)
            ->where('o.status',6)
            ->join('user u','u.id = o.user_id')
            ->field('o.id,o.user_id,u.nickname,o.pay_price')
            ->sum('o.pay_price');
        dump($pay);
        dump($refound);
//        dump($order_list);
    }

    public function techn_yeji(Request $request){
        $param = $request->param();

        $star = strtotime('2023-07-01');
        $end = time();
        if (!empty($param['star'])){
            $star = strtotime($param['star']);
        }
        if (!empty($param['end'])){
            $star = strtotime($param['end']);
        }
        $techn = Db::name('order')->where('shi',140100)->where('status',6)->where('add_time','between',$star.','.$end)->column('techn_id');
        $info = [];
        foreach ($techn as $value){
            $info[$value]['price'] = Db::name('order')->where('status',6)->where('add_time','between',$star.','.$end)->where('techn_id',$value)->sum('price');
        }


        foreach ($info as $k=>$v){
            $info[$k]['name'] = Db::name('techn')->where('id',$k)->value('nickname');
        }

        usort($info, 'cmp');
        for ($i=0;$i<10;$i++){
            $result[$i] = $info[$i];
        }
        dump($result);


    }
    public function isqufix(){
//        $ids = Db::name('user')->where('is_qu',0)->where('yongjin2','>',0)->column('id');
        $ids = Db::name('user')->where('is_qu',0)->where('yongjin','>',0)->column('id');
        foreach ($ids as $value){
                Db::name('user')->where('id',$value)->update(['is_qu'=>1]);
        }
    }

    public function techn_time(){
        TechnService::TechnPreTimey(527);
    }

    public function hejinsend(){
        $order_id = 15754;
        $send = Db::name('email_list')->where('proxy_id','in','9,999')->where('status',1)->column('open_id');
        dump($send);die;

        $order = Db::name('order')->where('id',$order_id)->find();
//        $value = Db::name('user_weixin')->where('user_id',$order['user_id'])->value('openid');

        $value = 'opx6C6vD4elzA71_uMmlvAxovti8';
//        foreach ($send as $value){
            if (!empty($value)){
                SendMuLogic::send_mu($value,$order);
            }
//        }
//        SendMuLogic::send_mu($value,$order);

    }
    public function send_mu_new(){
        $order_id = 10859;
//        $order_id = 8850;
        $order = Db::name('order')->where('id',$order_id)->find();
        $proxy = Db::name('proxy')->where('qu',$order['qu'])->find();
        if (empty($proxy)){
            $proxy = Db::name('proxy')->where('shi',$order['shi'])->find();
        }

        $send = Db::name('email_list')->where('proxy_id','in',[$proxy['proxy_id'],999])->where('status',1)->select();
//        dump($send);die;
        $value = Db::name('user_weixin')->where('user_id',6205)->value('openid');
//        $value = 'opx6C6vD4elzA71_uMmlvAxovti8';
        SendMuLogic::send_mu_new($value,$order);
    }


    public function get_today_money(){
        $list = Db::name('techn_zzf')->where('status',1)->where('add_time','>',1688140800)->column('cash_id');
        $in = implode(',',$list);
        $money = Db::name('money_cash')->where('id','in',$in)->sum('pay_money');
        $dd = Db::name('money_cash')->where('id','in',$in)->select();
        dump($money);
        dump($dd);
    }
    public function huan_add(){
        $params['lng'] = 113.05742;
        $params['lat'] = 36.05928;
        $ni_dili_data = http_curl('https://restapi.amap.com/v3/geocode/regeo?output=json&location='.$params['lng'].','.$params['lat'].'&key='.GaodeService::$web_api_key);
        $ni_dili_data = json_decode($ni_dili_data, true);
        if($ni_dili_data['status'] == 1){
            dump($ni_dili_data);
        }
    }
    public function n_talk_add(){
        $insert = [];
        $techn_list = Db::name('techn')->where('county','140882')->column('id');
        dump($techn_list);
        foreach ($techn_list as $value){
//            dump(Db::name('talk')->where('techn_id',$value)->find());die;

            if (empty(Db::name('talk')->where('techn_id',$value)->find())){
                $num = rand(5,10);
                for ($i = 0 ;$i < $num ;$i ++){
                    $insert[] = [
                        'techn_id'=>$value,
                        'service_level'=>5,
                        'title_ids'=>'[1,2,3,4,5]',
                        'add_time'=>rand(1672546214,1686024614)
                    ];
                }
            }
        }
        Db::name('talk')->insertAll($insert);
    }

    public function luyin(){
        $phone_t = 13383515396;
        $phone_u = 18803414141;

    }

    public function send_dw(){
        $res_sms = aliyun_send_sms("LTAI5tCfyuqK4o58i6MH3qH2","xXOnPRM4tMimqDVR4e1Ms5crn0lUtP",15035514195,"摩小妹",'SMS_461570126',null);
    }


    public function order_num(){
        $list = Db::name('techn')->where('orders_num','<',10)->column('id,orders_num');
        foreach ($list as $key=>$value){
            $add = $value + rand(15,25);
            Db::name('techn')->where('id',$key)->update(['orders_num'=>$add]);
        }
    }
    public function shenhe(){

        $time = strtotime('2023-5-31 23:59:59');
        $list = Db::name('money_cash')->where('add_time','<',$time)->where('identity_type','techn')->where('status',0)->select();
        $list_sum = Db::name('money_cash')->where('add_time','<',$time)->where('identity_type','techn')->where('status',0)->sum('money');
        foreach ($list as $key=>$value){
            $list[$key]['lock'] = Db::name('techn')->where('id',$value['identity_id'])->value('lock_money');
            $list[$key]['sheng'] = Db::name('techn')->where('id',$value['identity_id'])->value('lock_money') - $value['money'];

            if (empty($list[$key]['lock'])){
                unset($list[$key]);
            }
        }
        foreach ($list as $value){
            Db::name('money_cash')->where('id',$value['id'])->update(['status'=>1]);
            Db::name('techn')->where('id',$value['identity_id'])->update(['lock_money'=>$value['sheng']]);
        }




    }

    public function send_mu(){
        SendMuLogic::send_mu('opx6C6vD4elzA71_uMmlvAxovti8',['order_id'=>6389],6205);
    }
    public function lists(Request $request){
        $result['code'] = -1;
        $result['msg'] = "非法请求";
        $params = $this->data_post;
        $params = $request->param();


//        这是要注释的
        $params['page'] = isset($params['page']) ? $params['page'] : 1;
        $params['lat'] = 37.8718150000;
        $params['lng'] = 112.6003200000;
        $params['city'] = 141002;
        $this->user['id'] = 6205;

        //表单验证
        $validate = $this->validate(
            $params,
            [
                'city' => 'require',
                'lng' => 'require',
                'lat' => 'require',
                'page' => 'require'
            ],
            [
                'city.require' => '请选择城市',
                'lng.require' => '坐标信息有误',
                'lat.require' => '坐标信息有误',
                'page.require' => '分页有误'
            ]
        );

//        if(true !== $validate)
//        {
//            echo json_encode(['code' => -1, 'msg' => $validate]);
//            exit();
//        }
//        如果该城市有县级列表,去掉该市的县


        $qu = Db::name('proxy')->where('shi',$params['city'])->where('is_xian',1)->column('qu');
        if(!empty($qu)){
            $map = [
                'T.city' => $params['city'],
                'T.county' => ['not in',$qu],
                'T.work_status' => ['in', '1,2']
            ];
        }else{
            $map = [
                'T.county' => $params['city'],
                'T.work_status' => ['in', '1,2']
            ];
        }
        if(!empty($params['nickname']))
        {
            $map['T.nickname'] = ['like','%'.$params['nickname'].'%'];
        }

        if(!empty($params['class_id'])){
            $map['T.service_class_id']=$params['class_id'];
        }
        $orderdec='asc';
        if(!empty($params['dis'])){
            if($params['dis']==2){
                $orderdec='desc';
            }
        }

        if(!empty($params['work_status'])){
            $techn_ids=Db::name('order')->where(['status'=>['in','0,1,2,3,4,5'],'order_model'=>0])->column('techn_id');
            $map['work_status']=1;
            if($params['work_status']==1){//可预约
                $map['T.id']=['in',$techn_ids];
            }else{
                $map['T.id']=['not in',$techn_ids];

            }
        }
// 		$map['work_status']=1;
        $field_lat = 'TL.lat';
        $field_lng = 'TL.lng';
        $lat = $params['lat'];
        $lng = $params['lng'];

        $list_data = Db::name('techn')
            ->alias('T')
            ->join('__TECHN_LAST__ TL', 'T.id = TL.techn_id', 'LEFT')
            ->field("T.*, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance")
        ;
// 		if(!empty($params['work_status'])){
// 		    if($params['work_status']==1){//可预约
// 		        $list_data=$list_data->join('order o','o.techn_id=T.id and o.status not in (0,1,2,3,4,5) and o.order_model=0');
// 		    }else{
// 		        $list_data=$list_data->join('order o','o.techn_id=T.id and o.status in (0,1,2,3,4,5) and o.order_model=0');
// 		    }
// 		},(select  beiy  from jx_order where T.id=jx_order.techn_id and order_model=0 and status in(0,1,2,3,4,5) limit 1) as work_count
        $list_data=$list_data->where($map)->order('work_status asc,pre_time_y asc, distance '.$orderdec)
            ->limit(($params['page']-1)*10,10);


// 		$sql=$list_data->fetchsql(true)->select();echo $sql;exit;

        $list_data=$list_data->select();
        if (empty($list_data)){
            $map['T.county'] = $map['T.city'];
            unset($map['T.city']);
            $list_datas = Db::name('techn')
                ->alias('T')
                ->join('__TECHN_LAST__ TL', 'T.id = TL.techn_id', 'LEFT')
                ->field("T.*, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance")
            ;
            $list_datas=$list_datas->where($map)->order('work_status asc,pre_time_y asc, distance '.$orderdec)
                ->limit(($params['page']-1)*10,01);
            $list_data=$list_datas->select();

        }

        if(!empty($list_data))
        {
            //遍历处理
            foreach($list_data as $key => $value)
            {

                //获取技师等级图标 收藏数  评论数
                $level = Db::name('techn_last')->where('techn_id',$value['id'])->find();
                $level_info = Db::name('techn_level')->where('id',$level['level_id'])->find();
                if (!empty($level_info))
                    $level_url = '/static/'.$level_info['rank'].'x.png';
                else
                    $level_url = '';

                $list_data[$key]['level_url'] = $level_url;

//                $list_data[$key]['collect_num'] = rand(20,80);
//                是新人
                if (time() - $value['add_time'] < 259200){
                    $list_data[$key]['is_new'] = 1;
                }else{
                    $list_data[$key]['is_new'] = 0;
                }
                //是销冠
                $guan = Db::name('techn_last')->order('total_result desc')->where('city',$params['city'])->where('techn_id','<>','299')->limit(0,3)->column('techn_id');
                if (!empty($guan) && in_array($value['id'],$guan)){
                    $list_data[$key]['is_guan'] = 1;
                }else{
                    $list_data[$key]['is_guan'] = 0;
                }
                //是热门
                $hot = Db::name('techn_last')->order('total_result desc')->where('city',$params['city'])->where('techn_id','<>','299')->limit(4,5)->column('techn_id');
                if (!empty($hot) && in_array($value['id'],$hot)){
                    $list_data[$key]['is_hot'] = 1;
                }else{
                    $list_data[$key]['is_hot'] = 0;
                }
                $talk_num = Db::name('talk')->where('techn_id',$value['id'])->count('id');
                $all_xing = Db::name('talk')->where('techn_id',$value['id'])->sum('service_level');
                if (!empty($all_xing) && !empty($talk_num)){
                    $xing = round($all_xing/$talk_num,1);
                }else{
                    $xing = '4.'.rand(0,9);
                }
                $list_data[$key]['xing'] = $xing;

                if (isset($this->user['id'])){
                    $collect_list = Db::name('user')->where('id',$this->user['id'])->value('collect_techn');
                    $collect_list_arr = json_decode($collect_list,true);
                    if (!empty($collect_list_arr) && in_array($value['id'],$collect_list_arr)){
                        $list_data[$key]['collect_status'] = 1;
                    }else{
                        $list_data[$key]['collect_status'] = 0;
                    }
                }else{
                    $list_data[$key]['collect_status'] = 0;
                }
                $list_data[$key]['talk_num'] = Db::name('talk')->where('techn_id',$value['id'])->column('count(id)')[0];



                //处理工作形象照片
                $list_data[$key]['work_img'] = request()->domain().$value['work_img'];
                //处理个人生活照片
                $self_img_array = explode(",", $value['self_img']);
                foreach($self_img_array as $si_key => $si_value)
                {
                    $self_img_array[$si_key] = request()->domain().$si_value;
                }
                $list_data[$key]['self_img_array'] = $self_img_array;

                //处理技师工作状态
                $new_work_status = 0;
                $new_work_status_name = '';
                // if($value['work_status'] == 1)
                // {
                // 	//查询技师是否有下在进行中的订单
                // 	$run_order_info = Db::name('order')->where(['techn_id' => $value['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->find();
                // 	if(empty($run_order_info))
                // 	{
                // 		$new_work_status = 1;
                // 		$new_work_status_name = '可服务';
                // 	}else
                // 	{
                // 		$new_work_status = 2;
                // 		$new_work_status_name = '可预约';
                // 	}
                // }elseif($value['work_status'] == 2)
                // {
                // 	$new_work_status = 3;
                // 	$new_work_status_name = '休息中';
                // }

                if(!empty($value['pre_time_y'])){
                    if($value['pre_time_y']-time()>2700){
                        $new_work_status = 2;
                        $new_work_status_name = '可预约';
                    }else{
                        $new_work_status = 1;
                        $new_work_status_name = '可服务';
                    }
                }else{
                    $new_work_status = 3;
                    $new_work_status_name = '休息中';
                }
                $list_data[$key]['new_work_status'] = $new_work_status;
                $list_data[$key]['new_work_status_name'] = $new_work_status_name;
                $list_data[$key]['distance2'] = $value['distance'];
                //距离
                $int_distance = PriceNumberFormat($value['distance']/1000);
                $list_data[$key]['distance'] = $int_distance.'km';
                //判断是否可以预约
                $list_data[$key]['is_pre'] = $int_distance > 50 ? false : true;
                //技师最早可预约时间
                $pre_time = '';
                // $techn_pre_time = TechnService::TechnPreTime(['techn_id' => $value['id']]);
                // if(!empty($techn_pre_time))
                // {
                // 	$pre_time_array = array_merge_recursive($techn_pre_time[0]['time_slot'], $techn_pre_time[1]['time_slot'], $techn_pre_time[2]['time_slot']);
                // 	if(!empty($pre_time_array))
                // 	{
                // 		$pre_time = $pre_time_array[0]['time'];
                // 	}
                // }

                $daymsg='后天 ';


                if(!empty($value['pre_time_y'])){
                    if(date('d',$value['pre_time_y'])==date('d')){
                        $daymsg='今天 ';
                    }else if(date('d',$value['pre_time_y'])==date('d',time()+86400)){
                        $daymsg='明天 ';
                    }
                    $list_data[$key]['pre_time'] = $daymsg.date('H:i',$value['pre_time_y']);
                }else{
                    $list_data[$key]['pre_time'] = '';
                }

                //评价列表
                $talk_list = Db::name('talk')->where('techn_id',$value['id'])->order('add_time desc')->select();
                $talk_titles = Db::name('talk_title')->where('is_delete_time',0)->column('talk_title','id');
                if (!empty($talk_list)){
                    foreach ($talk_list as $kk => $vv){
                        $talk_list[$kk]['add_time'] = date('m-d',$vv['add_time']);
                        $vv['title_ids'] = json_decode($vv['title_ids']);
                        foreach ($vv['title_ids'] as $vvv){
                            $talk_list[$kk]['titles'][] = $talk_titles[$vvv];
                        }

                    }
                }
                $list_data[$key]['talk_list'] = $talk_list;
            }

            //获取优惠券
//            $params['user'] = $this->user;



            $result['code'] = 0;
            $result['msg'] = '请求成功';

//            如果用户选择城市不发券,自动加载的发券
            if (empty($params['chang_city'])){
                if (!empty($this->user) && $params['page'] <= 1){
                    $user = $this->user;
                    $give_quan = QuanLogic::give_quan($user['id'],$params['city']);
                    if ($give_quan['code'] == 0){
                        $result['give_quan'] = 1;
                    }else{
                        $result['give_quan'] = 0;
                    }
                    $result['msg'] = $give_quan['msg'];
                }
            }

            $result['data'] = $list_data;
            // $result['sql']=Db::name('techn')
            //   ->alias('T')
            //   ->join('__TECHN_LAST__ TL', 'T.id = TL.techn_id', 'LEFT')
            //   ->field("T.*, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance,(select  beiy  from jx_order where T.id=jx_order.techn_id and order_model=0 and status in(0,1,2,3,4,5) limit 1) as work_count")->where($map)->order('work_count asc,pre_time_y asc, distance '.$orderdec)->fetchsql(true)->select()
            //   ;

            $result['service_class']=db::name('service_class')->where('is_delete_time',0)->select();

        }else
        {
            if ($params['page'] > 1){
                $result['msg'] = "暂无更多数据";
            }else{
                $result['msg'] = "即将上线!";
            }
            $result['code'] = -1;
        }
        dump($result['data']);
        dump($result['service_class']);die;
        echo json_encode($result,256);

    }

    public function address(){
        $reson = GetAddressLogic::change_address(113.12952,36.20947 );
        dump($reson);die;
        if ($reson){
            $city = Db::name('area')->where('city_code',$reson)->where('lev',2)->find();
            $map['T.city'] = $city;
        }
        dump($map);
    }

    public function Refund($params = [])
    {
        $params['appid'] = 'wx8f727f4e82c3392b';
        $params['mch_id'] = 1640604023;
        $params['nonce_str'] = '6f9a8bf2b2d2358469b46195ff2bb22f';
        $params['sign_type'] = 'MD5';
        $params['transaction_id'] = 4200001843202306153063625170;
        $params['out_trade_no'] = 20230615163231985836;
        $params['out_refund_no'] = 20230615163231985836133106;
        $params['total_fee'] = 10;
        $params['refund_fee'] = 10;
        $params['refund_desc'] = '20230615163231985836订单退款0.10元';
        $params['sign'] = 'BFEB4B0F7572F3C1AC189077F81941E2';
        $params['refund_reason'] = '退款';


        $this->config['app_appid'] = '';
        $this->config['appid'] = 'wx8f727f4e82c3392b';
        $this->config['mini_appid'] = '';
        $this->config['mch_id'] = '1640604023';
        $this->config['key'] = '-----BEGIN CERTIFICATE-----
MIIEKDCCAxCgAwIBAgIUbNPZaJxobd5jJv19CF5Pi/8Pd1EwDQYJKoZIhvcNAQEL
BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
Q0EwHhcNMjMwNjE0MTAxMDAzWhcNMjgwNjEyMTAxMDAzWjCBgTETMBEGA1UEAwwK
MTYzOTE3NzI0NTEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMS0wKwYDVQQL
DCTlpKrljp/lkIjml63nvZHnu5znp5HmioDmnInpmZDlhazlj7gxCzAJBgNVBAYM
AkNOMREwDwYDVQQHDAhTaGVuWmhlbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAKPJTafkuYgsRXpMnzNvxUw0fJMzBdaAYlQXgyTpa/qQBOWk1DLNymea
mfpa+nXOWj+6TE3BHDA56CSF/Xu/QETQk+PmMcZhDTgfadZ0SvRLIidpnobeJiHu
12hUghX77nwiadpLv57ThJBshAOLY8pO7o4c2JJXrT/1+JEbHLI5S3cTEOdvm3+I
Bg8rQlVo5IRiAUZi9ASfGk2yPkVHiXDD31gDffnIOF6Mk9Q1T7pDJhLgXLMieDDW
pK8Tm2NonPCO/6iuZ5qTG71HPDMBJ4gobivFHqgijCPVzj2DP3fT+fEEAxCwivnx
am65ti2lJhMNlr8vfZncJB4ygdU6D+ECAwEAAaOBuTCBtjAJBgNVHRMEAjAAMAsG
A1UdDwQEAwID+DCBmwYDVR0fBIGTMIGQMIGNoIGKoIGHhoGEaHR0cDovL2V2Y2Eu
aXRydXMuY29tLmNuL3B1YmxpYy9pdHJ1c2NybD9DQT0xQkQ0MjIwRTUwREJDMDRC
MDZBRDM5NzU0OTg0NkMwMUMzRThFQkQyJnNnPUhBQ0M0NzFCNjU0MjJFMTJCMjdB
OUQzM0E4N0FEMUNERjU5MjZFMTQwMzcxMA0GCSqGSIb3DQEBCwUAA4IBAQA6uGZl
PsOLrzOWcIW5Hbu1IyhDi9WNYK7TcPsoIIvrmyKWuE1SyJAO4Iv7jpFMDLlDfW42
uxLTuJGLt+Ol8RDGlQ87x/Kf1POsjrm7DPyN3Zlk1J+O0/toS8sEq0pLmBy8NVae
4on+CyHUmC0v/4mrMzM8r62KMnf1EkrWp+ppal9FC0eGYgWSfEn9slsgv/tvpqE0
J+5Wxxp9HYSULJR3Z72cCHyjzD+hRseqttVDHdYRWD0iarKKRlEOTFQxM1xu4187
becx4e5WA4ZT97FILhVXz1jzLjDFqYg+5I1vdT0y98JCazx03x3veTfKr0VY4/0K
qonePZdOHpADNVBm
-----END CERTIFICATE-----';
        $this->config['apiclient_key'] = '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCjyU2n5LmILEV6
TJ8zb8VMNHyTMwXWgGJUF4Mk6Wv6kATlpNQyzcpnmpn6Wvp1zlo/ukxNwRwwOegk
hf17v0BE0JPj5jHGYQ04H2nWdEr0SyInaZ6G3iYh7tdoVIIV++58ImnaS7+e04SQ
bIQDi2PKTu6OHNiSV60/9fiRGxyyOUt3ExDnb5t/iAYPK0JVaOSEYgFGYvQEnxpN
sj5FR4lww99YA335yDhejJPUNU+6QyYS4FyzIngw1qSvE5tjaJzwjv+ormeakxu9
RzwzASeIKG4rxR6oIowj1c49gz930/nxBAMQsIr58WpuubYtpSYTDZa/L32Z3CQe
MoHVOg/hAgMBAAECggEAZ232FjJAX5flgCfm2SqaI1d529L6usx0S7pVXPfy8lYE
YajHQBXo3agp2ImfZMmdAGV7ThbG4EWRLY9X1c+enFZDLkXt5OLg4DImOgFSXBce
SFlQfMbIueEEMqQ7SfrATa/FvM7dAUV9j16Xt01NBTL3PtNEiJXJmHySLcA7TOgS
frVNW5RcZKayjEGXyLtAI8GHlh4uTr2SM67C0WPJrEoxyWEA2L7RzuPb5fnsU0pb
UALU4H2R3phTWMo01/buATbmSM0g64190G0NXfKSgpcK+0z2LMUcOKiwhTtMeHaI
b35Ury2clmBeWOVE7RfebgxHIUW97sGqFBdjofGXgQKBgQDZto6kieJSFvlL+66x
TwY8eDKznOBBI/5T9upVbc7XkxptaEXXpuzdkJg0u3HIuGcGjHst/3SX94h2njpa
DJom7iLZMWvsWr9LbrKmqqvYH4xIfKt8c5QJkH0HjLkAkNPPy0PWC0ejxhwtVfnp
4ziwXG/FLQ2GkG0K54GQFeXDSQKBgQDAlvaV5yXJ0Q0qthHdDqFyq+Nr8wjppuqg
M+mbH8Df/Ff3jK29ICYZT/3hUYMezvKV9BdJekYBAcHEAwha7AS/H4bQRtEy6PDj
51YV3dgiW3/FH6R69xAuJITMZO4cr0lMZCJz3/KSodIRLtjG3q1DiSW/YBj9AlXX
61QMuJRP2QKBgCgDanIJOYRW3pi9eBz0ZjQE72Sdh4XRZLPv5J+w39w1GB1VlciN
0GjkY2UFsmLuqVjFxvnsQnSPtRAAAr98I3TWPadncutsvk3R2ZnSMmU1XyYPa8Ei
yOl9Gc2ianoVJCjDtgMH7bHG/nTCoX0AGvIm+w/lOOAreS8Q33oo3CKpAoGAc3rR
9wa4CPCaRY8Q3Q1Fz52z62m6YWgd7dvS6po6q9QC50PqdaoOTkVBxVZ8GgAbQ8Eu
KXfw+++SwTbUTriRDA0aaE7eZ/l3YCC55Li2PbvBvHCBzt3QTOrG2kx23qpYeD7e
zb5uFHCFppoBkBW7rPBSuxMjSKqa0LKiHlKbU9kCgYEAjFlwH8cU4DbMul3KaAAM
dSL8nNdSt2rtATaP8dgy4jiR9BgkP78wmej1YC4VICC1kEqYvWj1uxzDT+WMp5c2
wf8Di5y5h8JAw6HIJUvhaIzQYYL2G8X9WtHLnwSNql45z9soFYhzsg7NGSJm0h+k
hihRYfiKoTq7on6ZXuv56t4=
-----END PRIVATE KEY-----';

        // 证书是否配置
//        if(empty($this->config['apiclient_cert']) || empty($this->config['apiclient_key']))
//        {
//            return ['code' => -1, 'msg' => '证书未配置'];
//        }

        // 退款原因
        $refund_reason = empty($params['refund_reason']) ? $params['order_no'].'订单退款'.$params['refund_price'].'元' : $params['refund_reason'];

        //$client_type = 'weixin';
        // appid，默认使用公众号appid
        //$appid = $this->PayAppID($client_type);
        $appid = $this->PayAppID($params['client_type']);

        // 请求参数
        $data = [
            'appid'             => $appid,
            'mch_id'            => $this->config['mch_id'],
            'nonce_str'         => md5(time().rand().$params['order_no']),
            'sign_type'         => 'MD5',
            'transaction_id'    => $params['trade_no'],
            'out_trade_no'      => $params['order_no'],
            'out_refund_no'     => $params['order_no'].GetRandomStr(6,'int'),
            'total_fee'         => (int) (($params['pay_price']*1000)/10),
            'refund_fee'        => (int) (($params['refund_price']*1000)/10),
            'refund_desc'       => $refund_reason,
        ];
        $data['sign'] = $this->GetSign($data);

        // 请求接口处理
        $result = $this->XmlToArray($this->HttpRequest('https://api.mch.weixin.qq.com/secapi/pay/refund', $this->ArrayToXml($data), true));
        if(isset($result['result_code']) && $result['result_code'] == 'SUCCESS' && isset($result['return_code']) && $result['return_code'] == 'SUCCESS')
        {
            // 统一返回格式
            $data = [
                'out_trade_no'  => isset($result['out_trade_no']) ? $result['out_trade_no'] : '',
                'trade_no'      => isset($result['transaction_id']) ? $result['transaction_id'] : (isset($result['err_code_des']) ? $result['err_code_des'] : ''),
                'buyer_user'    => isset($result['refund_id']) ? $result['refund_id'] : '',
                'refund_price'  => isset($result['refund_fee']) ? $result['refund_fee']/100 : 0.00,
                'return_params' => $result,
            ];
            return ['code' => 0, 'msg' => '退款成功', 'data' => $data];
        }


        $msg = is_string($result) ? $result : (empty($result['err_code_des']) ? '退款接口异常' : $result['err_code_des']);
        if(!empty($result['return_msg']))
        {
            $msg .= '-'.$result['return_msg'];
        }
        return ['code' => -1, 'msg' => $msg];
    }


    public function etrr(){
        $order['order'] = Db::name('order')->where('id',6013)->find();
        $order['pay']['pay_price'] = 0.1;
        $order['payment']['payment'] = 'wechatpay';
        $order['payment']['name'] = '订单支付';
        $return = self::OrderPayHandle($order);
        dump($return);

    }


    public static function OrderPayHandle($params = [])
    {
        //订单信息
        if(empty($params['order']))
        {
            return ['code' => -1, 'msg' => '资源不存在或已被删除'];
        }
        if($params['order']['status'] > 0 && $params['order']['status']!=8)
        {
            return ['code' => 0, 'msg' => '状态不可操作'];
        }
        // 支付方式
        if(empty($params['payment']))
        {
            return ['code' => -1, 'msg' => '支付方式有误'];
        }
        // 支付参数
        $pay_price = isset($params['pay']['pay_price']) ? $params['pay']['pay_price'] : 0;
        // 开启事务
        Db::startTrans();
        //写入支付日志
        $pay_log_id = Db::name('pay_log')->insertGetId([
            'order_id'      => $params['order']['id'],
            'trade_no'      => isset($params['pay']['trade_no']) ? $params['pay']['trade_no'] : '',
            'buyer_user'    => isset($params['pay']['buyer_user']) ? $params['pay']['buyer_user'] : '',
            'pay_price'     => $pay_price,
            'total_price'   => $params['order']['total_price'],
            'subject'       => isset($params['pay']['subject']) ? $params['pay']['subject'] : '订单支付',
            'payment'       => $params['payment']['payment'],
            'payment_name'  => $params['payment']['name'],
            'business_type' => 1,
            'add_time' => time()
        ]);

        if($pay_log_id <= 0)
        {
            Db::rollback();
            return ['code' => -1, 'msg' => '支付日志添加失败'];
        }
        die;
        //订单更新数据
        $upd_data = [
            'status' => 1,
            'pay_status' => 1,
            'pay_price' => $pay_price,
            'pay_time' => time(),
            'upd_time' => time()
        ];
        //更新订单状态
        if(!Db::name('order')->where(['id' => $params['order']['id']])->update($upd_data))
        {
            Db::rollback();
            return ['code' => -1, 'msg' => '订单更新失败'];
        }
        //添加状态日志
        $status_array = self::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
            'order_id' => $params['order']['id'],
            'original_status' => $params['order']['status'],
            'new_status' => $upd_data['status'],
            'msg' => '支付['.$status_array[$params['order']['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
            'identity_type' => 'system',
            'identity_id' => 0,
            'add_time' => time()
        ]);
        if($order_status_history_id <= 0)
        {
            Db::rollback();
            return ['code' => -1, 'msg' => '订单历史状态添加失败'];
        }
        //写入结算数据
        $balance_data = [];
        //结算剩余百分比
        $balance_surplus_scale = 100;
        //服务剩余费用
        $balance_surplus_price = $params['order']['price']-$params['order']['preferential_price'];
        //查询技师等级写入结算数据

        //渠道费
        $preferential_price=0;

        //查询技师信息
        $techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
        $orders_num = $techn_info['orders_num']+1;
        if($params['order']['preferential_price'] > 0){
            $quan = json_decode($params['order']['extension_data'],true);
            log::write($quan);
            $quan_status = Db::name('coupon')->where('id',$quan[0]['ext']['coupon_id'])->value('bear_one');
        }




        //上级返利

        $userupid=db::name('user_bd')->where('bduid',$techn_info['user_id'])->value('user_id');

        if(!empty($userupid) && $params['order']['budan_id'] == 0){

            //上级用户
            $user=db::name('user')->where('id',$userupid)->find();

            $techn_up=Db::name('techn')->where('user_id',$userupid)->find();

            $user_bd=db::name('user_bd')->where(['user_id'=>$userupid,'bduid'=>$techn_info['user_id']])->find();


            if(!empty($techn_up)){//技师推技师
                $bl=$user_bd['bd_bl2'];
            }else{//技师推用户
                $bl=$user_bd['bd_bl'];
            }

            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0&&$no_money>0){
                $balance_data[] = [
                    'balance_type' => 4,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $userupid,
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '技师分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];

                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;

            }
        }

        $user_bl = 0;
        //用户分佣
        if($params['order']['poster_id']>0 && $params['order']['poster_id']!=$params['order']['user_id'] && $params['order']['budan_id'] == 0){
            $user=db::name('user')->where('id',$params['order']['poster_id'])->find();
            $daytime=strtotime(date('Y-m-d'));
            $add_time=$user['add_time'];
            $bl=$user['share_bl'];
            $user_bl=$bl;
            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0){
                $balance_data[] = [
                    'balance_type' => 3,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $params['order']['poster_id'],
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '用户分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>1
                ];
                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;
            }
        }

        if($params['order']['price']>0){
            //查询技师实时数据
            $techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();

            if(!empty($techn_last_info))
            {
                //技师分成比例
                $techn_divide_into = $techn_last_info['divide_into'];
                //技师分成金额
                if (isset($quan_status) && $quan_status != 1){
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($balance_surplus_price));
                }else{
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($balance_surplus_price+$params['order']['preferential_price']));
                }
                if ($user_bl > 1){
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price-$params['order']['preferential_price']));
                }
                //技师服务费用结算数据
                $techn_service_data = [
                    'balance_type' => 1,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'techn',
                    'identity_id' => $params['order']['techn_id'],
                    'divide_into' => $techn_divide_into,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
                    'msg' => '技师分成',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];
                $balance_surplus_scale -= $techn_service_data['divide_into'];
                $balance_surplus_price -= $techn_service_data['no_money'];
                $balance_data[] = $techn_service_data;
            }
        }






        if($params['order']['price']>0){

            //查看机构结算数据
            $proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
            if(!empty($proxy_info))
            {
                if($balance_surplus_price >= 0.01)
                {
                    //机构分成比例
                    $proxy_commission = $proxy_info['commission'];
                    //机构分成金额
                    $proxy_no_money = PriceNumberFormat(($proxy_commission/100)*($params['order']['price']-$params['order']['preferential_price']));
                    //机构结算数据
                    $proxy_service_data = [
                        'balance_type' => 1,
                        'order_id' => $params['order']['id'],
                        'identity_type' => 'proxy',
                        'identity_id' => $proxy_info['proxy_id'],
                        'divide_into' => $proxy_commission,
                        'price' => $params['order']['price']-$params['order']['preferential_price'],
                        'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
                        'msg' => '机构分成',
                        'add_time' => time(),
                        'upd_time' => time(),
                        'khtype'=>2
                    ];
                    $balance_surplus_scale -= $proxy_service_data['divide_into'];
                    $balance_surplus_price -= $proxy_service_data['no_money'];
                    $balance_data[] = $proxy_service_data;
                }
            }
            //系统平台结算数据
            if($balance_surplus_price >= 0.01)
            {
                $balance_data[] = [
                    'balance_type' => 1,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'system',
                    'identity_id' => 0,
                    'divide_into' => $balance_surplus_scale,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $balance_surplus_price,
                    'msg' => '平台分成',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];
            }


        }
        if ($params['order']['travel_price'] > 0 ){
            //技师出行费用结算数据
            $balance_data[] = [
                'balance_type' => 2,
                'order_id' => $params['order']['id'],
                'identity_type' => 'techn',
                'identity_id' => $params['order']['techn_id'],
                'divide_into' => 100,
                'price' => $params['order']['travel_price'],
                'no_money' => $params['order']['travel_price'],
                'msg' => '技师出行',
                'add_time' => time(),
                'upd_time' => time(),
                'khtype'=>2
            ];
        }

        if(!empty($balance_data))
        {
            Db::name('techn')->where('id',$params['order']['techn_id'])->update(['orders_num'=>$orders_num]);

            $balance_count = Db::name('balance')->insertAll($balance_data);
            if($balance_count <= 0)
            {
                Db::rollback();
                return ['code' => -1, 'msg' => '结算数据添加失败'];
            }
//            //增加技师周期内绩效
//            $have_result = Db::name('techn_last')->where('techn_id',$params['order']['techn_id'])->field('total_result')->find();
//            $now_result = $have_result['total_result']+$params['order']['price'];
//            $last_re = Db::name('techn_last')->where('techn_id',$params['order']['techn_id'])->update(['temp_result'=>$now_result]);
//            if (!$last_re){
//                Db::rollback();
//                return ['code' => -1, 'msg' => '结算数据添加失败'];
//            }
        }


        //提交事务
        Db::commit();
        if(!empty($techn_info))
        {


            TechnService::TechnPreTimey($params['order']['techn_id']);

            //  if($techn_info['work_status']==1){
            //   //电话通知技师接单
            //   ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', $techn_info['mobile'], 'TTS_269350009');
            //  }else{
            //      if($params['order']['pre_start_time']-time()<3600){
            //       ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', $techn_info['mobile'], 'TTS_269350009');
            //      }else{

            //走队列
            //创建任务： 项目命名空间\模块\文件夹\控制器@方法
            // 		$job = "app\service\QueuesService@ivrCall";
            // 		//延时时间
            // 		$delayed_second = 0;
            // 		$queues_data = ['mobile' => $techn_info['mobile']];
            // 		\think\Queue::later($delayed_second, $job, $queues_data, 'ivrCall');
            //      }
            //  }


            //  if($params['order']['pre_start_time']-time()<3600){
            //      $second=0;
            ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', $techn_info['mobile'], 'TTS_269350009');
            //      db::name('order')->where('id',$params['order']['id'])->setInc('tel_num',1);
            //  }else{
            $second=180;
            $job = "app\service\QueuesService@ivrCall";
            //延时时间
            $delayed_second = 300;
            $queues_data = ['id' => $params['order']['id'],'mobile'=>$techn_info['mobile']];
            \think\Queue::later($second, $job, $queues_data, 'ivrCall');
//         		\think\Queue::later($delayed_second, $job, $queues_data, 'ivrCall');
            //  }

            //  电话次数队列

            //创建任务： 项目命名空间\模块\文件夹\控制器@方法  10分钟后退款
            $job = "app\service\QueuesService@orderCall";
            //延时时间
            $delayed_second = 600;
            $queues_data = ['id' => $params['order']['id'],'mobile'=>$techn_info['mobile']];
            \think\Queue::later($delayed_second, $job, $queues_data, 'orderCall');



            //微信模板消息
            //查询技师关联用户公众号的openid
            $openid = Db::name('user_weixin')->where(['user_id' => $techn_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
            if(!empty($openid))
            {
                /////////////上方测试，下方正式/////////
                //查询订单详情
                $order_detail_title = Db::name('order_detail')->where(['order_id' => $params['order']['id']])->column('title');
                //  $order_detail_title = implode(',', $order_detail_title);
                $order_detail_title_new='服务项目:'.implode(',',$order_detail_title);
                //  foreach ($order_detail_title as $k=>$v){
                //      $order_detail_title_new.="\n ".($k+1).'.'.$v;
                //  }
                //查询下单人
                $order_address = Db::name('order_address')->where(['order_id' => $params['order']['id']])->find();
                //查询用户
                $user_info = Db::name('user')->where(['id' => $params['order']['user_id']])->find();
                $tem_msg['touser'] = $openid;
                $tem_msg['template_id'] = 'uhmQUK0MNOSOTHFHmf66Z6OR0piSyTwXNmLYkJl4dBs';
                $tem_msg['miniprogram'] = [
                    'appid' => TechnWeixinService::$mini_appid,
                    'pagepath' => 'pages/order/orderdetail?order_id='.$params['order']['id']
                ];

                if($params['order']['budan_id']>0){
                    $first='您好，有客户补单成功';
                    db::name('order')->where('id',$params['order']['budan_id'])->update(['status'=>8]);
                }else{
                    $first='您好，有客户下单成功';
                }

                $tem_msg['data'] = [
                    'first' => [
                        'value' => $first,
                        'color' => '#173177'
                    ],
                    'keyword1' => [
                        'value' => $order_detail_title_new,
                        'color' => '#173177'
                    ],
                    'keyword2' => [
                        'value' => $order_address['name'],
                        'color' => '#173177'
                    ],
                    'keyword3' => [
                        'value' => substr_replace($order_address['mobile'], '****', 3, 4),
                        'color' => '#173177'
                    ],
                    'keyword4' => [
                        'value' => substr_replace($user_info['mobile'], '****', 3, 4),
                        'color' => '#173177'
                    ],
                    'keyword5' => [
                        'value' => $order_address['address'].$order_address['address_des'],
                        'color' => '#173177'
                    ],
                    'remark' => [
                        'value' => '请及时接单',
                        'color' => '#173177'
                    ]
                ];
                UserWeixinService::send_wx_web_tem_msg($tem_msg);
            }
            $order = Db::name('order')->where('id',$params['order']['id'])->find();
//            发送邮件通知

            $proxy = Db::name('proxy')->where('shi',$order['shi'])->find();
            $send = Db::name('email_list')->where('proxy_id','in',[$proxy['proxy_id'],999])->where('status',1)->column('email');
            $xm = Db::name('order_detail')->where('order_id',$order['id'])->find();
            $techn = Db::name('techn')->where('id',$order['techn_id'])->find();
            $user_name = Db::name('user')->where('id',$order['user_id'])->find();
//            $msg = '['.$proxy['user_name'].']订单通知: 用户:'.$user_name.',在 '.date('m-d H:i',$order['pay_time']).','.$xm['title'].' *'.$xm['buy_number'].',金额 '.$order['price'].",<br>
//            订单号为".$order['order_no'].",<br>
//            车费为:".$order['travel_price']."<br>
//            待接单技师:".$techn['nickname'].",<br>
//            联系电话:".$techn['mobile'].",<br>
//            已通知技师接单.";

            $msg = '所属城市-【'.$proxy['user_name'].'】<br>
            技师昵称:  '.$techn['nickname'].'<br>       
            联系电话:  '.$techn['mobile'].'<br>
            下单客户:  '.$user_name['nickname'].' <br>  
            联系电话：'.$user_name['mobile'].'<br><br>
           
            
            下单时间：'.date('m-d H:i',$order['pay_time']).'<br>
            服务时间：'.date('m-d H:i',$order['pre_start_time']).'-'.date('H:i',$order['pre_end_time']).'<br><br>
            
            项目名称：'.$xm['title'].'(¥'.$xm['price'].') *'.$xm['buy_number'].'<br>      
            往返路程：¥'.$order['distance'].'km<br>
            往返车费：¥'.$order['travel_price'].'元<br>
            订单总价：¥'.$order['pay_price'].'元<br>';
            $subject = "订单通知";
//            Mail::mailTo($send,$subject,$msg);
            //走队列
            //创建任务： 项目命名空间\模块\文件夹\控制器@方法
            $job = "app\service\QueuesSendEmail@send_email";
            //延时时间
            $delayed_second = 3;
            $queues_data = ['to' => $send,'title'=>$subject,'content'=>$msg];
            \think\Queue::later($delayed_second, $job, $queues_data, 'send_email');

        }
        return ['code' => 0, 'msg' => '支付成功'];
    }

    public function fenc(){

        $params['order'] = Db::name('order')->where('id',5752)->find();
        //写入结算数据
        $balance_data = [];
        //结算剩余百分比
        $balance_surplus_scale = 100;
        //服务剩余费用
        $balance_surplus_price = $params['order']['price']-$params['order']['preferential_price'];
        //查询技师等级写入结算数据

        //渠道费
        $preferential_price=0;

        //查询技师信息
        $techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
        $orders_num = $techn_info['orders_num']+1;
        if($params['order']['preferential_price'] > 0){
            $quan = json_decode($params['order']['extension_data'],true);
            log::write($quan);
            $quan_status = Db::name('coupon')->where('id',$quan[0]['ext']['coupon_id'])->value('bear_one');
        }




        //上级返利

        $userupid=db::name('user_bd')->where('bduid',$techn_info['user_id'])->value('user_id');

        if(!empty($userupid)){

            //上级用户
            $user=db::name('user')->where('id',$userupid)->find();

            $techn_up=Db::name('techn')->where('user_id',$userupid)->find();

            $user_bd=db::name('user_bd')->where(['user_id'=>$userupid,'bduid'=>$techn_info['user_id']])->find();


            if(!empty($techn_up)){//技师推技师
                $bl=$user_bd['bd_bl2'];
            }else{//技师推用户
                $bl=$user_bd['bd_bl'];
            }

            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0&&$no_money>0){
                $balance_data[] = [
                    'balance_type' => 4,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $userupid,
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '技师分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];

                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;

            }
        }

        $user_bl = 0;
        //用户分佣
        if($params['order']['poster_id']>0 && $params['order']['poster_id']!=$params['order']['user_id']){
            $user=db::name('user')->where('id',$params['order']['poster_id'])->find();
            $daytime=strtotime(date('Y-m-d'));
            $add_time=$user['add_time'];
            $bl=$user['share_bl'];
            $user_bl=$bl;
            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0){
                $balance_data[] = [
                    'balance_type' => 3,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $params['order']['poster_id'],
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '用户分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>1
                ];
                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;
            }
        }

        if($params['order']['price']>0){
            //查询技师实时数据
            $techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();

            if(!empty($techn_last_info))
            {
                //技师分成比例
                $techn_divide_into = $techn_last_info['divide_into'];
                //技师分成金额
                if (isset($quan_status) && $quan_status != 1){
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($balance_surplus_price));
                }else{
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($balance_surplus_price+$params['order']['preferential_price']));
                }
                if ($user_bl > 1){
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price-$params['order']['preferential_price']));
                }
                //技师服务费用结算数据
                $techn_service_data = [
                    'balance_type' => 1,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'techn',
                    'identity_id' => $params['order']['techn_id'],
                    'divide_into' => $techn_divide_into,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
                    'msg' => '技师分成',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];
                $balance_surplus_scale -= $techn_service_data['divide_into'];
                $balance_surplus_price -= $techn_service_data['no_money'];
                $balance_data[] = $techn_service_data;
            }
        }






        if($params['order']['price']>0){

            //查看机构结算数据
            $proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
            if(!empty($proxy_info))
            {
                if($balance_surplus_price >= 0.01)
                {
                    //机构分成比例
                    $proxy_commission = $proxy_info['commission'];
                    //机构分成金额
                    $proxy_no_money = PriceNumberFormat(($proxy_commission/100)*($params['order']['price']-$params['order']['preferential_price']));
                    //机构结算数据
                    $proxy_service_data = [
                        'balance_type' => 1,
                        'order_id' => $params['order']['id'],
                        'identity_type' => 'proxy',
                        'identity_id' => $proxy_info['proxy_id'],
                        'divide_into' => $proxy_commission,
                        'price' => $params['order']['price']-$params['order']['preferential_price'],
                        'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
                        'msg' => '机构分成',
                        'add_time' => time(),
                        'upd_time' => time(),
                        'khtype'=>2
                    ];
                    $balance_surplus_scale -= $proxy_service_data['divide_into'];
                    $balance_surplus_price -= $proxy_service_data['no_money'];
                    $balance_data[] = $proxy_service_data;
                }
            }
            //系统平台结算数据
            if($balance_surplus_price >= 0.01)
            {
                $balance_data[] = [
                    'balance_type' => 1,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'system',
                    'identity_id' => 0,
                    'divide_into' => $balance_surplus_scale,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $balance_surplus_price,
                    'msg' => '平台分成',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];
            }
            //技师出行费用结算数据
            $balance_data[] = [
                'balance_type' => 2,
                'order_id' => $params['order']['id'],
                'identity_type' => 'techn',
                'identity_id' => $params['order']['techn_id'],
                'divide_into' => 100,
                'price' => $params['order']['travel_price'],
                'no_money' => $params['order']['travel_price'],
                'msg' => '技师出行',
                'add_time' => time(),
                'upd_time' => time(),
                'khtype'=>2
            ];

        }
        dump($balance_data);



        //        //查询技师信息
//        $techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
//        $orders_num = $techn_info['orders_num']+1;
//        if($params['order']['preferential_price'] > 0){
//            $quan = json_decode($params['order']['extension_data'],true);
//            log::write($quan);
//            $quan_status = Db::name('coupon')->where('id',$quan[0]['ext']['coupon_id'])->value('bear_one');
//        }
//
//        if($params['order']['price']>0){
//            //查询技师实时数据
//            $techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();
//
//            if(!empty($techn_last_info))
//            {
//                if(!empty($techn_last_info['divide_into'])){
//                    //技师分成比例
//                    $techn_divide_into = $techn_last_info['divide_into'];
//                    //技师分成金额
//                    if (isset($quan_status) && $quan_status != 1){
//                        $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price-$params['order']['preferential_price']));
//                    }else{
//                        $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price));
//                        $balance_surplus_price = $params['order']['price']-$params['order']['preferential_price'];
//
//                    }
//                    //技师服务费用结算数据
//                    $techn_service_data = [
//                        'balance_type' => 1,
//                        'order_id' => $params['order']['id'],
//                        'identity_type' => 'techn',
//                        'identity_id' => $params['order']['techn_id'],
//                        'divide_into' => $techn_divide_into,
//                        'price' => $params['order']['price']-$params['order']['preferential_price'],
//                        'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
//                        'msg' => '技师分成',
//                        'add_time' => time(),
//                        'upd_time' => time(),
//                        'khtype'=>2
//                    ];
//                    $balance_surplus_scale -= $techn_service_data['divide_into'];
//                    $balance_surplus_price -= $techn_service_data['no_money'];
//                    $balance_data[] = $techn_service_data;
//                }else{
//                    //如果技师实时信息存在查询对应等级
//                    //检查等级条件
//                    $techn_level_map = [
//                        'is_delete_time' => 0,
//                        'rank' => $techn_last_info['divide_rank'],
//                        'proxy_id'=>0
//                    ];
//                    $techn_level_info = Db::name('techn_level')->where($techn_level_map)->find();
//                    if(!empty($techn_level_info))
//                    {
//                        //如果技师等级存在
//                        //结算服务分成
//                        if($balance_surplus_price >= 0.01)
//                        {
//                            //技师分成比例
//                            $techn_divide_into = $techn_level_info['divide_into'];
//                            //技师分成金额
//                            $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$params['order']['price']);
//                            //技师服务费用结算数据
//                            $techn_service_data = [
//                                'balance_type' => 1,
//                                'order_id' => $params['order']['id'],
//                                'identity_type' => 'techn',
//                                'identity_id' => $params['order']['techn_id'],
//                                'divide_into' => $techn_divide_into,
//                                'price' => $params['order']['price']-$params['order']['preferential_price'],
//                                'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
//                                'msg' => '技师分成',
//                                'add_time' => time(),
//                                'upd_time' => time(),
//                                'khtype'=>2
//                            ];
//                            $balance_surplus_scale -= $techn_service_data['divide_into'];
//                            $balance_surplus_price -= $techn_service_data['no_money'];
//                            $balance_data[] = $techn_service_data;
//                        }
//                    }
//                }
//            }
//        }
//        //用户分佣
//        if($params['order']['poster_id']>0 && $params['order']['poster_id']!=$params['order']['user_id']){
//            $user=db::name('user')->where('id',$params['order']['poster_id'])->find();
//            $daytime=strtotime(date('Y-m-d'));
//            $add_time=$user['add_time'];
//            $bl=$user['share_bl'];
//            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
//            if($bl>0){
//                $balance_data[] = [
//                    'balance_type' => 3,
//                    'order_id' => $params['order']['id'],
//                    'identity_type' => 'user',
//                    'identity_id' => $params['order']['poster_id'],
//                    'divide_into' => $bl,
//                    'price' => $params['order']['price']-$params['order']['preferential_price'],
//                    'no_money' => $no_money,
//                    'msg' => '用户分佣',
//                    'add_time' => time(),
//                    'upd_time' => time(),
//                    'khtype'=>1
//                ];
//                $preferential_price+=$no_money;
//                $balance_surplus_price -= $no_money;
//            }
//        }
//
//        //上级返利
//
//        $userupid=db::name('user_bd')->where('bduid',$techn_info['user_id'])->value('user_id');
//
//        if(!empty($userupid)){
//
//            //上级用户
//            $user=db::name('user')->where('id',$userupid)->find();
//
//            $techn_up=Db::name('techn')->where('user_id',$userupid)->find();
//
//            $user_bd=db::name('user_bd')->where(['user_id'=>$userupid,'bduid'=>$techn_info['user_id']])->find();
//
//
//            if(!empty($techn_up)){//技师推技师
//                $bl=$user_bd['bd_bl2'];
//            }else{//技师推用户
//                $bl=$user_bd['bd_bl'];
//            }
//
//            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
//            if($bl>0&&$no_money>0){
//                $balance_data[] = [
//                    'balance_type' => 4,
//                    'order_id' => $params['order']['id'],
//                    'identity_type' => 'user',
//                    'identity_id' => $userupid,
//                    'divide_into' => $bl,
//                    'price' => $params['order']['price']-$params['order']['preferential_price'],
//                    'no_money' => $no_money,
//                    'msg' => '技师分佣',
//                    'add_time' => time(),
//                    'upd_time' => time(),
//                    'khtype'=>2
//                ];
//
//                $preferential_price+=$no_money;
//                $balance_surplus_price -= $no_money;
//
//            }
//        }
//
//
//        //用户-》技师
//        // 		$userinfo=db::name('user')->where('id',$params['order']['user_id'])->find();
//        // 		if(!empty($userinfo['upid'])){
//
//        // 		    $user_bd=db::name('user_bd')->where(['user_id'=>$userinfo['upid'],'bduid'=>$userinfo['id']])->find();
//
//        // 		    $bl=$user_bd['bd_bl3'];
//
//        // 	        $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
//        // 		    if($bl>0&&$no_money>0){
//        // 		        $balance_data[] = [
//        //     				'balance_type' => 4,
//        //     				'order_id' => $params['order']['id'],
//        //     				'identity_type' => 'user',
//        //     				'identity_id' => $userinfo['upid'],
//        //     				'divide_into' => $bl,
//        //     				'price' => $params['order']['price']-$params['order']['preferential_price'],
//        //     				'no_money' => $no_money,
//        //     				'msg' => '技师分佣',
//        //     				'add_time' => time(),
//        //     				'upd_time' => time(),
//        //     				'khtype'=>2
//        //     			];
//
//        //     			$preferential_price+=$no_money;
//        // 		    }
//        // 		}
//
//
//
//        //技师出行费用结算数据
//        $balance_data[] = [
//            'balance_type' => 2,
//            'order_id' => $params['order']['id'],
//            'identity_type' => 'techn',
//            'identity_id' => $params['order']['techn_id'],
//            'divide_into' => 100,
//            'price' => $params['order']['travel_price'],
//            'no_money' => $params['order']['travel_price'],
//            'msg' => '技师出行',
//            'add_time' => time(),
//            'upd_time' => time(),
//            'khtype'=>2
//        ];
//
//
//        if($params['order']['price']>0){
//
//            //查看机构结算数据
//            $proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
//            if(!empty($proxy_info))
//            {
//                if($balance_surplus_price >= 0.01)
//                {
//                    //机构分成比例
//                    $proxy_commission = 100-$proxy_info['commission']-$techn_divide_into;
//                    //机构分成金额
//                    $proxy_no_money = PriceNumberFormat(($proxy_commission/100)*($params['order']['price']-$params['order']['preferential_price']));
//                    //机构结算数据
//                    $proxy_service_data = [
//                        'balance_type' => 1,
//                        'order_id' => $params['order']['id'],
//                        'identity_type' => 'proxy',
//                        'identity_id' => $proxy_info['proxy_id'],
//                        'divide_into' => $proxy_commission,
//                        'price' => $params['order']['price']-$params['order']['preferential_price'],
//                        'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
//                        'msg' => '机构分成',
//                        'add_time' => time(),
//                        'upd_time' => time(),
//                        'khtype'=>2
//                    ];
//                    $balance_surplus_scale -= $proxy_service_data['divide_into'];
//                    $balance_surplus_price -= $proxy_service_data['no_money'];
//                    $balance_data[] = $proxy_service_data;
//                }
//            }
//            //系统平台结算数据
//            if($balance_surplus_price >= 0.01)
//            {
//                $balance_data[] = [
//                    'balance_type' => 1,
//                    'order_id' => $params['order']['id'],
//                    'identity_type' => 'system',
//                    'identity_id' => 0,
//                    'divide_into' => $balance_surplus_scale,
//                    'price' => $params['order']['price']-$params['order']['preferential_price'],
//                    'no_money' => $balance_surplus_price,
//                    'msg' => '平台分成',
//                    'add_time' => time(),
//                    'upd_time' => time(),
//                    'khtype'=>2
//                ];
//            }
//
////
//        }


    }
    public function position(){
        $ni_dili_data = http_curl('https://restapi.amap.com/v3/geocode/regeo?output=json&location=112.6003200000,37.8718150000&key=f189b2a1b49842d004618b13dfb55464');
        $ni_dili_data = json_decode($ni_dili_data, true);
        dump($ni_dili_data);
    }
    public function fix_talk(){
        $techn_list = Db::name('techn')->where('city',140800)->where('work_status','<>',3)->column('id');
        foreach ($techn_list as $value){
            $num = rand(2,4);
            for ($i = 0 ;$i < $num ;$i ++){
                $insert[] = [
                    'techn_id'=>$value,
                    'service_level'=>4,
                    'title_ids'=>'[1,2,3,4,5]',
                    'add_time'=>rand(1672546214,1686024614)
                ];

            }
            Db::name('talk')->insertAll($insert);

        }

    }


    public function talk_add(){
        $insert = [];
        $techn_list = Db::name('techn')->column('id');
        foreach ($techn_list as $value){
            dump(Db::name('talk')->where('techn_id',$value)->find());die;

            if (empty(Db::name('talk')->where('techn_id',$value)->find())){
                $num = rand(5,10);
                for ($i = 0 ;$i < $num ;$i ++){
                    $insert[] = [
                        'techn_id'=>$value,
                        'service_level'=>rand(5),
                        'title_ids'=>'[1,2,3,4,5]',
                        'add_time'=>rand(1672546214,1686024614)
                    ];
                }
            }
        }
        Db::name('talk')->insertAll($insert);
    }

    public function quan(){
        die;
        $this->user = ['id'=>6879];
        $params['order'] = Db::name('order')->where('id',5496)->find();
        dump($params['order']);
        //写入结算数据
        $balance_data = [];
        //结算剩余百分比
        $balance_surplus_scale = 100;
        //服务剩余费用
        $balance_surplus_price = $params['order']['price'];
        //查询技师等级写入结算数据

        //渠道费
        $preferential_price=0;

        //查询技师信息
        $techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
        $orders_num = $techn_info['orders_num']+1;
        if($params['order']['preferential_price'] > 0){
            $quan = json_decode($params['order']['extension_data'],true);
            log::write($quan);
            $quan_status = Db::name('coupon')->where('id',$quan[0]['ext']['coupon_id'])->value('bear_one');
        }

        //用户分佣
        if($params['order']['poster_id']>0 && $params['order']['poster_id']!=$params['order']['user_id']){
            $user=db::name('user')->where('id',$params['order']['poster_id'])->find();
            $daytime=strtotime(date('Y-m-d'));
            $add_time=$user['add_time'];
            $bl=$user['share_bl'];
            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0){
                $balance_data[] = [
                    'balance_type' => 3,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $params['order']['poster_id'],
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '用户分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>1
                ];
                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;
            }
        }

        if($params['order']['price']>0){
            //查询技师实时数据
            $techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();

            if(!empty($techn_last_info))
            {
                if(!empty($techn_last_info['divide_into'])){
                    //技师分成比例
                    $techn_divide_into = $techn_last_info['divide_into'];
                    //技师分成金额
                    if (isset($quan_status) && $quan_status == 0){
                        $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price-$params['order']['preferential_price']));
                    }else{
                        $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price));
                        $balance_surplus_price = $params['order']['price']-$params['order']['preferential_price'];

                    }
                    //技师服务费用结算数据
                    $techn_service_data = [
                        'balance_type' => 1,
                        'order_id' => $params['order']['id'],
                        'identity_type' => 'techn',
                        'identity_id' => $params['order']['techn_id'],
                        'divide_into' => $techn_divide_into,
                        'price' => $params['order']['price']-$params['order']['preferential_price'],
                        'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
                        'msg' => '技师分成',
                        'add_time' => time(),
                        'upd_time' => time(),
                        'khtype'=>2
                    ];
                    $balance_surplus_scale -= $techn_service_data['divide_into'];
                    $balance_surplus_price -= $techn_service_data['no_money'];
                    $balance_data[] = $techn_service_data;
                }else{
                    //如果技师实时信息存在查询对应等级
                    //检查等级条件
                    $techn_level_map = [
                        'is_delete_time' => 0,
                        'rank' => $techn_last_info['divide_rank'],
                        'proxy_id'=>0
                    ];
                    $techn_level_info = Db::name('techn_level')->where($techn_level_map)->find();
                    if(!empty($techn_level_info))
                    {
                        //如果技师等级存在
                        //结算服务分成
                        if($balance_surplus_price >= 0.01)
                        {
                            //技师分成比例
                            $techn_divide_into = $techn_level_info['divide_into'];
                            //技师分成金额
                            $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$params['order']['price']);
                            //技师服务费用结算数据
                            $techn_service_data = [
                                'balance_type' => 1,
                                'order_id' => $params['order']['id'],
                                'identity_type' => 'techn',
                                'identity_id' => $params['order']['techn_id'],
                                'divide_into' => $techn_divide_into,
                                'price' => $params['order']['price'],
                                'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
                                'msg' => '技师分成',
                                'add_time' => time(),
                                'upd_time' => time(),
                                'khtype'=>2
                            ];
                            $balance_surplus_scale -= $techn_service_data['divide_into'];
                            $balance_surplus_price -= $techn_service_data['no_money'];
                            $balance_data[] = $techn_service_data;
                        }
                    }
                }
            }
        }


        //上级返利

        $userupid=db::name('user_bd')->where('bduid',$techn_info['user_id'])->value('user_id');

        if(!empty($userupid)){

            //上级用户
            $user=db::name('user')->where('id',$userupid)->find();

            $techn_up=Db::name('techn')->where('user_id',$userupid)->find();

            $user_bd=db::name('user_bd')->where(['user_id'=>$userupid,'bduid'=>$techn_info['user_id']])->find();


            if(!empty($techn_up)){//技师推技师
                $bl=$user_bd['bd_bl2'];
            }else{//技师推用户
                $bl=$user_bd['bd_bl'];
            }

            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0&&$no_money>0){
                $balance_data[] = [
                    'balance_type' => 4,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $userupid,
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '技师分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];

                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;

            }
        }


        //用户-》技师
        // 		$userinfo=db::name('user')->where('id',$params['order']['user_id'])->find();
        // 		if(!empty($userinfo['upid'])){

        // 		    $user_bd=db::name('user_bd')->where(['user_id'=>$userinfo['upid'],'bduid'=>$userinfo['id']])->find();

        // 		    $bl=$user_bd['bd_bl3'];

        // 	        $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
        // 		    if($bl>0&&$no_money>0){
        // 		        $balance_data[] = [
        //     				'balance_type' => 4,
        //     				'order_id' => $params['order']['id'],
        //     				'identity_type' => 'user',
        //     				'identity_id' => $userinfo['upid'],
        //     				'divide_into' => $bl,
        //     				'price' => $params['order']['price']-$params['order']['preferential_price'],
        //     				'no_money' => $no_money,
        //     				'msg' => '技师分佣',
        //     				'add_time' => time(),
        //     				'upd_time' => time(),
        //     				'khtype'=>2
        //     			];

        //     			$preferential_price+=$no_money;
        // 		    }
        // 		}



        //技师出行费用结算数据
        $balance_data[] = [
            'balance_type' => 2,
            'order_id' => $params['order']['id'],
            'identity_type' => 'techn',
            'identity_id' => $params['order']['techn_id'],
            'divide_into' => 100,
            'price' => $params['order']['travel_price'],
            'no_money' => $params['order']['travel_price'],
            'msg' => '技师出行',
            'add_time' => time(),
            'upd_time' => time(),
            'khtype'=>2
        ];


        if($params['order']['price']>0){

            //查看机构结算数据
            $proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
            if(!empty($proxy_info))
            {
                if($balance_surplus_price >= 0.01)
                {
                    //机构分成比例
                    $proxy_commission = 100-$proxy_info['commission']-$techn_divide_into;
                    //机构分成金额
                    $proxy_no_money = PriceNumberFormat(($proxy_commission/100)*($params['order']['price']-$params['order']['preferential_price']));
                    //机构结算数据
                    $proxy_service_data = [
                        'balance_type' => 1,
                        'order_id' => $params['order']['id'],
                        'identity_type' => 'proxy',
                        'identity_id' => $proxy_info['proxy_id'],
                        'divide_into' => $proxy_commission,
                        'price' => $params['order']['price'],
                        'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
                        'msg' => '机构分成',
                        'add_time' => time(),
                        'upd_time' => time(),
                        'khtype'=>2
                    ];
                    $balance_surplus_scale -= $proxy_service_data['divide_into'];
                    $balance_surplus_price -= $proxy_service_data['no_money'];
                    $balance_data[] = $proxy_service_data;
                }
            }
            //系统平台结算数据
            if($balance_surplus_price >= 0.01)
            {
                $balance_data[] = [
                    'balance_type' => 1,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'system',
                    'identity_id' => 0,
                    'divide_into' => $balance_surplus_scale,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $balance_surplus_price,
                    'msg' => '平台分成',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];
            }

//
        }
        dump($balance_data);

    }



    public function deal_orders_num(){
        $list = Db::name('techn')->where('city',340100)->column('orders_num','id');
        dump($list);die;
        foreach ($list as $key => $value){
            if ($value < 100){
                $sum = Db::name('order')->where('techn_id',$key)->count('id');
                $num = $value + rand(107,187);
                Db::name('techn')->where('id',$key)->update(['orders_num'=>$num]);
            }
        }
    }
    public function get_ca(){
        $info = cache('yinsi_phone_15035514195');
        dump($info);


        //解绑关系
//        $args = [
//            'poolKey' => 'FC100000167170034',
//            'subsId' => $info['subsId'],
//            'secretNo' => $info['secretNo']
//        ];
//        \yinsi\Privacy::UnbindSubscription($args);
    }

    public function techn_time_no(){
        //处理第一条时间自动选择
        //dump($params);
        $params['techn_id'] = 299;
        //当前时间
        $current_time = time();
        //预约间隔时间(15分钟)
        $interval_time = $current_time+900;
        //最终预约时间
        $final_time = $interval_time;
        //技师预约时间节点
        $reservation_node = [];
        //如果技师id存在查询技师
        $techn_info = [];
        if(!empty($params['techn_id']))
        {
            $techn_info = Db::name('techn')->where(['id' => $params['techn_id']])->find();
            if(!empty($techn_info))
            {
                $techn_info['no_pre_hour_slot'] = !empty($techn_info['no_pre_hour_slot']) ? json_decode($techn_info['no_pre_hour_slot'], true) : [];
                //查询技师已预约的订单
                $order_list = Db::name('order')->where(['techn_id' => $techn_info['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->select();
                if(!empty($order_list))
                {
                    foreach($order_list as $key => $value)
                    {
                        if(!empty($value['pre_start_time']) && !empty($value['pre_end_time']))
                        {
                            //处理时间节点
                            /*if($value['service_time'] > 0)
                            {
                                //如果开始服务
                                $pre_start_time = $value['service_time'];
                                $pre_end_time = $value['service_time']+($value['buy_number_duration']*60)+900;
                            }else
                            {*/
                            $pre_start_time = $value['pre_start_time'];
                            $pre_end_time = $value['pre_end_time']+900;
                            /*}*/
                            for($j = $pre_start_time; $j <= $pre_end_time; $j += 1800)
                            {
                                $reservation_node[] = date('Y-m-d H:i:s', $j);
                            }
                        }
                    }
                }
            }
        }
//        dump($techn_info);die;
        $list_data = [];
        $week_arr = ["周日","周一","周二","周三","周四","周五","周六"];
        //开始时间
        $start_time = strtotime(date('Y-m-d', time()));
        //结束时间
        $end_time = strtotime(date('Y-m-d', strtotime("+2 day")));
        //算出开始时间与结束时间中间间隔的时间
        $key = 0;
        for($i = $start_time; $i <= $end_time; $i += 86400)
        {
            $list_data[$key]['day'] = date('m-d', $i);
            $list_data[$key]['week'] = $week_arr[date("w", $i)];

            $time_slot = [];
            $slot_key = 0;
            //如果技师接单状态
            if(!empty($techn_info) && $techn_info['work_status'] == 1)
            {
                //开始时间段
                $start_slot = strtotime(date('Y-m-d', $i).' 00:00:00');
                //结束时间段
                $end_slot = strtotime(date('Y-m-d', $i).' 23:59:59');
                //判断是否选择接单开始时间与结束时间
                $work_start_hour = !empty($techn_info['work_start_hour']) ? strtotime(date('Y-m-d', $i).' '.$techn_info['work_start_hour'].':00') : strtotime(date('Y-m-d', $i).' 00:00:00');

                $work_end_hour = !empty($techn_info['work_end_hour']) ? strtotime(date('Y-m-d', $i).' '.$techn_info['work_end_hour'].':00') : strtotime(date('Y-m-d', $i).' 23:59:59');
                for($j = $start_slot; $j <= $end_slot; $j += 1800)
                {
                    //如果大于当前时间才显示
                    if($work_start_hour > $work_end_hour)
                    {
                        if($j >= $final_time && ($j >= $work_start_hour || $j <= $work_end_hour) && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
                        {
                            $time_slot[$slot_key]['time'] = date('H:i', $j);
                            $time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
                            $slot_key++;
                        }
                    }elseif ($work_start_hour < $work_end_hour) {
                        if($j >= $final_time && $j >= $work_start_hour && $j <= $work_end_hour && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
                        {
                            $time_slot[$slot_key]['time'] = date('H:i', $j);
                            $time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
                            $slot_key++;
                        }
                    }else
                    {
                        if($j >= $final_time && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
                        {
                            $time_slot[$slot_key]['time'] = date('H:i', $j);
                            $time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
                            $slot_key++;
                        }
                    }
                    if (!empty($time_slot)){
                        break;
                    }
                }
            }
            $list_data[$key]['time_slot'] = $time_slot;
            $key++;
            break;
        }
        $result['code'] = 0;
        $result['msg'] = "请求成功";
        $result['data'] = $list_data;
        echo json_encode($result);

    }
    public function order_list(){
        $params['user']['id'] = 6205;
        $params['status'] = 0;
        $params['page'] = 1;
        $map = [
            'user_id' => $params['user']['id'],
            'order_model' => 0,
            'user_is_delete_time' => 0
        ];
        if($params['status'] > 0)
        {
            switch ($params['status']) {
                //待支付
                case 1:
                    $map['status'] = 0;
                    break;
                //待服务
                case 2:
                    $map['status'] = ['in', '1,2,3,4'];
                    break;
                //服务中
                case 3:
                    $map['status'] = 5;
                    break;
                //已完成
                case 4:
                    $map['status'] = 6;
                case 5:
                    $map['status'] = 9;
                    break;
            }
        }
        $list_data = Db::name('order')->where($map)->order('id desc')->limit(($params['page']-1)*10,10)->select();
        if(!empty($list_data))
        {
            //订单状态
            $status_array = OrderService::$status_array;
            //遍历处理
            foreach($list_data as $key => $value)
            {
                //订单状态
                $list_data[$key]['status_name'] = !empty($status_array[$value['status']]['name']) ? $status_array[$value['status']]['name'] : '';
                //查询订单详情
                $order_detail = Db::name('order_detail')->where(['order_id' => $value['id'],'showtype'=>1])->select();
                if(!empty($order_detail))
                {
                    foreach($order_detail as $k => $v)
                    {
                        $order_detail[$k]['images'] = request()->domain().$v['images'];
                    }
                }
                $list_data[$key]['order_detail'] = $order_detail;
                //查询服务技师
                $techn_info = Db::name('techn')->field('nickname')->where(['id' => $value['techn_id']])->find();
                $list_data[$key]['techn_info'] = $techn_info;
                //预约时间
                $list_data[$key]['pre_start_time_time'] = !empty($value['add_time']) ? date('Y-m-d H:i:s', $value['add_time']) : '';

                $list_data[$key]['jz_type']=2;
                $list_data[$key]['bd_type']=2;
                $list_data[$key]['up_type']=2;
                $list_data[$key]['contact_type']=2;

                // if($params['user']['id']==1264||$params['user']['id']==1551||$params['user']['id']==976||$params['user']['id']==5){
                if($value['status']==5){
                    $list_data[$key]['jz_type']=1;
                    $list_data[$key]['up_type']=1;
                }else
                    if($value['status']==6&&time()-$value['pre_end_time']<600){
                        $list_data[$key]['jz_type']=1;
                    }

                if($value['status']==9){
                    $list_data[$key]['bd_type']=1;
                }

                // }
                if($value['status']>=2&&$value['status']<=5){
                    $list_data[$key]['contact_type']=1;
                }elseif($value['status']==6&&time()-$value['pre_end_time']<600){
                    $list_data[$key]['contact_type']=1;
                }


            }
            $result['code'] = 0;
            $result['msg'] = "请求成功";
            $result['data'] = $list_data;
        }else
        {
            $result['code'] = -1;
            $result['msg'] = "暂无数据";
        }
        dump($list_data);die;
        echo json_encode($result,256);
    }

//点赞/取消点赞
    public function collect(Request $request){
        $user['id'] = 6205;
        $status['data']['id'] = 299;
        $list_data = Db::name('talk')->where('techn_id',299)->column('count(id)')[0];
        dump($list_data);die;
//        $this->IsLogin(); //验证登录
        $user = $this->user;
        $status = $request->param();
        $userinfo = Db::name('user')->where('id',$user['id'])->find();
        $like = json_decode($userinfo['collect_techn']);

        if (!empty($like) && in_array($status['data']['id'],$like)){
            $key = array_search($status['data']['id'],$like);
            unset($like[$key]);
            $return['msg'] = '取消点赞成功';
            $return['code'] = 0;
        }else{
            $like[] = $status['data']['id'];
            $return['msg'] = '点赞成功';
            $return['code'] = 1;
        }
        $json = json_encode($like);
        $update = ['collect_techn'=>$json];

        $result = Db::name('user')->where('id',$user['id'])->update($update);
        if ($result){

        }else{
            $return = [
                'code'=>-1,
                'msg'=>'系统繁忙,请重试',
                'data'=>$status
            ];
        }
        return json_encode($return,256);

    }

    //评论
    public function talk(Request $request){
        $param = $request->param();
        $param['user_id'] = 6205;
        $param['service_level'] = 5;
        $param['titile_ids'] = '1,2,3,4,5';
        $param['content'] = '112233';



    }



    public function listss(){
        if(!empty($params['nickname']))
        {
            $map['T.nickname'] = ['like','%'.$params['nickname'].'%'];
        }

        if(!empty($params['class_id'])){
            $map['T.service_class_id']=$params['class_id'];
        }
        $orderdec='asc';
        if(!empty($params['dis'])){
            if($params['dis']==2){
                $orderdec='desc';
            }
        }

        if(!empty($params['work_status'])){
            $techn_ids=db::name('order')->where(['status'=>['in','0,1,2,3,4,5'],'order_model'=>0])->column('techn_id');
            $map['work_status']=1;
            if($params['work_status']==1){//可预约
                $map['T.id']=['in',$techn_ids];
            }else{
                $map['T.id']=['not in',$techn_ids];

            }
        }
// 		$map['work_status']=1;
        $field_lat = 'TL.lat';
        $field_lng = 'TL.lng';
//        $lat = $params['lat'];
//        $lng = $params['lng'];
        $params['page'] = 1;
        $lat = 112.6003200000;
        $lng = 37.8718150000;

        $list_data = Db::name('techn')
            ->alias('T')
            ->join('__TECHN_LAST__ TL', 'T.id = TL.techn_id', 'LEFT')
            ->field("T.*, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance")
        ;
// 		if(!empty($params['work_status'])){
// 		    if($params['work_status']==1){//可预约
// 		        $list_data=$list_data->join('order o','o.techn_id=T.id and o.status not in (0,1,2,3,4,5) and o.order_model=0');
// 		    }else{
// 		        $list_data=$list_data->join('order o','o.techn_id=T.id and o.status in (0,1,2,3,4,5) and o.order_model=0');
// 		    }
// 		},(select  beiy  from jx_order where T.id=jx_order.techn_id and order_model=0 and status in(0,1,2,3,4,5) limit 1) as work_count
        $list_data=$list_data->order('work_status asc,pre_time_y asc, distance '.$orderdec)
            ->limit(($params['page']-1)*10,10);

// 		$sql=$list_data->fetchsql(true)->select();echo $sql;exit;

        $list_data=$list_data->select();

        if(!empty($list_data))
        {
            //遍历处理
            foreach($list_data as $key => $value)
            {
                //获取技师等级图标 收藏数  评论数
                $level = Db::name('techn_last')->where('techn_id',$value['id'])->find();
                $level_info = Db::name('techn_level')->where('id',$level['level_id'])->find();
                if (!empty($level_info))
                    $level_url = '/static/'.$level_info['rank'].'x.png';
                else
                    $level_url = '';
                $list_data[$key]['level_url'] = $level_url;
                $list_data[$key]['collect_num'] = rand(20,80);
                $list_data[$key]['talk_num'] = rand(1,10);


                //处理工作形象照片
                $list_data[$key]['work_img'] = request()->domain().$value['work_img'];
                //处理个人生活照片
                $self_img_array = explode(",", $value['self_img']);
                foreach($self_img_array as $si_key => $si_value)
                {
                    $self_img_array[$si_key] = request()->domain().$si_value;
                }
                $list_data[$key]['self_img_array'] = $self_img_array;

                //处理技师工作状态
                $new_work_status = 0;
                $new_work_status_name = '';
                // if($value['work_status'] == 1)
                // {
                // 	//查询技师是否有下在进行中的订单
                // 	$run_order_info = Db::name('order')->where(['techn_id' => $value['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->find();
                // 	if(empty($run_order_info))
                // 	{
                // 		$new_work_status = 1;
                // 		$new_work_status_name = '可服务';
                // 	}else
                // 	{
                // 		$new_work_status = 2;
                // 		$new_work_status_name = '可预约';
                // 	}
                // }elseif($value['work_status'] == 2)
                // {
                // 	$new_work_status = 3;
                // 	$new_work_status_name = '休息中';
                // }

                if(!empty($value['pre_time_y'])){
                    if($value['pre_time_y']-time()>2700){
                        $new_work_status = 2;
                        $new_work_status_name = '可预约';
                    }else{
                        $new_work_status = 1;
                        $new_work_status_name = '可服务';
                    }
                }else{
                    $new_work_status = 3;
                    $new_work_status_name = '休息中';
                }
                $list_data[$key]['new_work_status'] = $new_work_status;
                $list_data[$key]['new_work_status_name'] = $new_work_status_name;
                $list_data[$key]['distance2'] = $value['distance'];
                //距离
                $int_distance = PriceNumberFormat($value['distance']/1000);
                $list_data[$key]['distance'] = $int_distance.'km';
                //判断是否可以预约
                $list_data[$key]['is_pre'] = $int_distance > 50 ? false : true;
                //技师最早可预约时间
                $pre_time = '';
                // $techn_pre_time = TechnService::TechnPreTime(['techn_id' => $value['id']]);
                // if(!empty($techn_pre_time))
                // {
                // 	$pre_time_array = array_merge_recursive($techn_pre_time[0]['time_slot'], $techn_pre_time[1]['time_slot'], $techn_pre_time[2]['time_slot']);
                // 	if(!empty($pre_time_array))
                // 	{
                // 		$pre_time = $pre_time_array[0]['time'];
                // 	}
                // }

                $daymsg='后天 ';


                if(!empty($value['pre_time_y'])){
                    if(date('d',$value['pre_time_y'])==date('d')){
                        $daymsg='今天 ';
                    }else if(date('d',$value['pre_time_y'])==date('d',time()+86400)){
                        $daymsg='明天 ';
                    }
                    $list_data[$key]['pre_time'] = $daymsg.date('H:i',$value['pre_time_y']);
                }else{
                    $list_data[$key]['pre_time'] = '';
                }
                dump($list_data);
                die;
            }
            $result['code'] = 0;
            $result['msg'] = "请求成功";
            $result['data'] = $list_data;
            // $result['sql']=Db::name('techn')
            //   ->alias('T')
            //   ->join('__TECHN_LAST__ TL', 'T.id = TL.techn_id', 'LEFT')
            //   ->field("T.*, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance,(select  beiy  from jx_order where T.id=jx_order.techn_id and order_model=0 and status in(0,1,2,3,4,5) limit 1) as work_count")->where($map)->order('work_count asc,pre_time_y asc, distance '.$orderdec)->fetchsql(true)->select()
            //   ;

            $result['service_class']=db::name('service_class')->where('is_delete_time',0)->select();

        }else
        {
            $result['code'] = -1;
            $result['msg'] = "暂无数据";
        }
    }

    public function orders_num(){
        $params['order']['price']= 100;
        $params['order']['techn_id'] = 299;
        $techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();

        if($params['order']['price']>0){
            //查询技师实时数据
            $techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();

            if(!empty($techn_last_info)) {
                if (!empty($techn_last_info['divide_into'])) {
                    //技师分成比例
                    $techn_divide_into = $techn_last_info['divide_into'];
                    //技师分成金额
                    $techn_no_money = 10;
                    //技师服务费用结算数据
                    $techn_service_data = [
                        'balance_type' => 1,
                        'identity_type' => 'techn',
                        'identity_id' => $params['order']['techn_id'],
                        'divide_into' => $techn_divide_into,
                        'price' => $params['order']['price'],
                        'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
                        'msg' => '技师分成',
                        'add_time' => time(),
                        'upd_time' => time(),
                        'khtype' => 2
                    ];
                }
            }
            $order = $techn_info['orders_num']+1;
            Db::name('techn')->where('id',$params['order']['techn_id'])->update(['orders_num'=>$order]);

            dump($order);
        }
    }
    public function zhifubaotixian(){
        require_once '../request/AlipayFundTransUniTransferRequest.php';

        /**

         * 证书类型AopCertClient功能方法使用测试，特别注意支付宝根证书预计2037年会过期，请在适当时间下载更新支付更证书

         * 1、execute 证书模式调用示例

         * 2、sdkExecute 证书模式调用示例

         * 3、pageExecute 证书模式调用示例

         */

//1、execute 使用

        $aop = new AopCertClient ();

        $appCertPath = "应用证书路径(要确保证书文件可读)，例如：/home/admin/cert/appCertPublicKey.crt";

        $alipayCertPath = "支付宝公钥证书路径(要确保证书文件可读)，例如：/home/admin/cert/alipayCertPublicKey_RSA2.crt";

        $rootCertPath = "支付宝根证书路径(要确保证书文件可读)，例如：/home/admin/cert/alipayRootCert.crt";

        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';

        $aop->appId = '你的appid';

        $aop->rsaPrivateKey = '你的应用私钥';

        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);//调用getPublicKey从支付宝公钥证书中提取公钥

        $aop->apiVersion = '1.0';

        $aop->signType = 'RSA2';

        $aop->postCharset='utf-8';

        $aop->format='json';

        $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内

        $aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号

        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号

        $request = new AlipayFundTransUniTransferRequest();

        $arrData = [

            'out_biz_no' => 'Test'.time().rand(10000,99999), // 商户端的唯一订单号，对于同一笔转账请求，商户需保证该订单号唯一。

// 单笔无密转账到支付宝账户固定

// TRANS_ACCOUNT_NO_PWD 产品取值范围[0.1,100000000]

// STD_RED_PACKET [0.01,100000000]

            'trans_amount' => 0.1, // 订单总金额，单位为元，精确到小数点后两位,

            'product_code' => 'TRANS_ACCOUNT_NO_PWD',

            'biz_scene' => 'DIRECT_TRANSFER', // B2C现金红包、单笔无密转账到支付宝/银行卡

            'order_title' => '测试提现', // 转账业务的标题，用于在支付宝用户的账单里显示

            'payee_info' => [

                'identity' => 'xxxxx',// 参与方的唯一标识

                'identity_type' => 'ALIPAY_LOGON_ID', // 支付宝登录号，支持邮箱和手机号格式

                'name' => 'xxxxx', // 参与方真实姓名，如果非空，将校验收款支付宝账号姓名一致性。当identity_type=ALIPAY_LOGON_ID时，本字段必填。

            ],

            'remark' => '测试提现'

        ];

        $request->setBizContent(json_encode($arrData,JSON_UNESCAPED_UNICODE));

        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

        $resultCode = $result->$responseNode->code;

        if(!empty($resultCode)&&$resultCode == 10000){

            echo "成功";

        } else {

            echo "失败";

        }

        print_r($result);
    }


    public function email(Request $request){
        $order =Db::name('order')->where('id',4366)->find();

        $proxy = Db::name('proxy')->where('shi',$order['shi'])->find();
        $send = '846315369@qq.com';
        $xm = Db::name('order_detail')->where('order_id',$order['id'])->find();
        $techn = Db::name('techn')->where('id',$order['techn_id'])->find();
        $user_name = Db::name('user')->where('id',$order['user_id'])->find();
//        $msg = '['.$proxy['user_name'].']订单通知: 用户:'.$user_name.',在 '.date('m-d H:i',$order['pay_time']).','.$xm['title'].' *'.$xm['buy_number'].',金额 '.$order['price'].",订单号为".$order['order_no']."<br>
//待接单技师:".$techn['nickname'].',联系电话:'.$techn['mobile'].',已通知技师接单.';
//        $subject = "订单通知";
        $msg = '订单通知-【'.$proxy['user_name'].'】<br>
            下单客户:  '.$user_name['nickname'].' <br>  
            联系电话：'.$user_name['mobile'].'<br><br>
            技师昵称:  '.$techn['nickname'].'<br>       
            联系电话:  '.$techn['mobile'].'<br>
            
            下单时间：'.date('m-d H:i',$order['pay_time']).'<br>
            服务时间：'.date('m-d H:i',$order['pre_start_time']).'<br><br>
            
            项目名称：'.$xm['title'].' *'.$xm['buy_number'].'<br>      
            往返路程：'.$order['distance'].'km<br>
            往返车费：'.$order['travel_price'].'元<br>
            订单总价：'.$order['price'].'元<br>';
        $subject = "订单通知";
        $re = Mail::mailTo($send,$subject,$msg);
        if ($re['code']){
            echo '发送成功';
        }else{
            echo $re['resion'];
        }

    }
//    获取验证码
    public function get_code_now(Request $request){
        $num = $request->param();
        $code = cache($num['num'].'_mobile_code');
        dump($code);
    }

    
}